﻿using System;
using System.Collections.Generic;
using System.Linq;
using Jink.Core.Handlers.Annotations;
using Jink.Core.Json;
using Jink.Core.Json.Values;
using Jink.Playground.Domain;
using Jink.Playground.MockData;
using XenoGears.Functional;
using XenoGears.Assertions;

namespace Jink.Playground
{
    [Resource("/lists?id={list}/items")]
    internal class ListItems
    {
        [Bind]
        private SPList _list = null;

        [Get]
        public IEnumerable<SPListItem> Get()
        {
            return Get(null);
        }

        [Get("?{qbe}")]
        public IEnumerable<SPListItem> Get(JsonValue qbe)
        {
            return _list.Items.Where(item => qbe.All(kvp =>
            {
                var field = item.Fields.Keys.SingleOrDefault(f => String.Compare(f, kvp.Key, true) == 0);
                return field != null && kvp.Value == item.Fields[field].ToJson();
            }));
        }

        [Post]
        public SPListItem Post(SPListItem listItem)
        {
            _list.ToDatabaseObject().Save();
            return listItem;
        }

        [Put]
        public SPListItem Put(SPListItem listItem)
        {
            listItem.Fields.ContainsKey("Id").AssertFalse();
            var nextId = _list.Items.MaxOrDefault(li => (int)li.Fields["Id"]) + 1;
            listItem.Fields["Id"] = nextId;

            _list.Items.Add(listItem);
            _list.ToDatabaseObject().Save();
            return listItem;
        }

        [Delete]
        public void Delete(SPListItem listItem)
        {
            _list.Items.Remove(listItem);
            _list.ToDatabaseObject().Save();
        }
    }
}
